import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Divider, Select, DatePicker, Modal } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import BatchUpload from '../../components/BatchUpload/Index';
import StepItem from '../../components/BatchUpload/StepItem';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';

const { RangePicker } = DatePicker;
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};
@connect(({ publicdata, loading, career }) => ({
  career,
  areaList: career.areaList,
  contList: career.contList,
  uploading: loading.effects['career/uploadFileWithProgress'],
  batchQuery: career.batchQuery,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  currentStep: career.currentStep,
  progressPercent: career.progressPercent,
  resultInfo: career.resultInfo,
  showProgress: career.showProgress,
}))
@Form.create()
class Batch extends React.PureComponent {
  activeKey;

  constructor(props) {
    super(props);
    this.state = {
      downTem: null,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;

    this.activeKey = location?.query?.activeKey;
    console.log(this.activeKey);
    dispatch({
      type: 'career/getAreaScope',
      payload: {},
    });
    this.clearModel();
  }

  componentWillUnmount() {
    this.clearModel();
  }

  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'career/updateModelData',
      payload: {
        currentStep: 0,
        progressPercent: 0,
        showProgress: false,
        batchQuery: {
          // 批量上传数据
          areaId: null,
          contType: null,
          progressPercent: 0,
        },
      },
    });
  };

  areaOnChange = value => {
    const { dispatch, form } = this.props;
    form.resetFields(['contTypes']);
    dispatch({
      type: 'career/getContTypeScope',
      payload: { areaId: value },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'career/updateModelData',
      payload: { currentStep },
    });

    if (!currentStep) {
      this.clearModel();
    }
  };

  // 下一步
  onNext = () => {
    // 接口
    const {
      dispatch,
      form: { validateFields },
      currentStep,
    } = this.props;
    validateFields((err, values) => {
      if (!err) {
        const newFieldsValue = values;
        Object.keys(values).forEach(key => {
          if (key === 'dateArr') {
            if (values.dateArr && values.dateArr.length) {
              newFieldsValue.startDate = values.dateArr[0].format('YYYY-MM-DD');
              newFieldsValue.endDate = values.dateArr[1].format('YYYY-MM-DD');
            }
            delete newFieldsValue[key];
          }
          newFieldsValue.conTypes = values.contTypes;
        });
        dispatch({
          type: 'career/fetchVerifyMatPkg',
          payload: newFieldsValue,
        }).then(res => {
          if (res.success && res.data.matPkgId) {
            delete newFieldsValue.conTypes;
            this.setState({
              downTem: { ...newFieldsValue, matPkgId: res.data.matPkgId, curStep: this.activeKey },
            });
            this.setCurrentstep(currentStep + 1);
          } else {
            Modal.warning({
              title: res.message,
              okText: '关闭',
              autoFocusButton: 'cancel',
              okType: 'default',
            });
          }
        });
      }
    });
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const { dispatch } = this.props;
    const { downTem } = this.state;
    // 需要携带参数即传：batchQuery，不需要传参可省略
    Object.entries(downTem).forEach(([key, value]) => {
      formData.append(key, value);
    });
    dispatch({
      type: 'career/uploadFileWithProgress',
      payload: formData,
    })
  };

  render() {
    const isExactDiv = () => (
      <div>
        <Divider dashed style={{ marginTop: 100 }} />
        <p style={{ margin: '0 auto', width: '50%', fontSize: 14, textAlign: 'left' }}>
          说明
          <br />
          （1）员工信息上传成功后，数据将流转到入职办理-已办理页面。
          <br />
          （2）如果上传员工信息中存在以下两种情况
          ①模板中必填项没有按照要求填写或者为空，②材料配置中存在附件类型的数据且为必填类型，那么数据将流转到入职办理-办理中页面，数据状态为材料不完整。
        </p>
      </div>
    );
    const {
      form,
      uploading,
      areaList,
      contList,
      currentStep,
      showProgress,
      progressPercent,
      resultInfo,
    } = this.props;
    const { getFieldDecorator } = form;
    const { downTem } = this.state;
    const dateFormat = 'YYYY-MM-DD';
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <StepItem title="选择地区">
            <Form layout="horizontal" style={{ margin: '40px auto 0', maxWidth: 500 }}>
              <Form.Item {...formItemLayout} label="派单时间">
                {getFieldDecorator('dateArr', {
                  rules: [{ type: 'array' }],
                })(
                  <RangePicker
                    style={{ width: '100%' }}
                    format={dateFormat}
                    placeholder={['开始日期', '结束日期']}
                  />
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="选择地区">
                {getFieldDecorator('areaId', {
                  rules: [{ required: true, message: '请选择地区' }],
                })(
                  <HOCSelect onChange={this.areaOnChange} placeholder="请选择地区">
                    {areaList.map(item => (
                      <Option key={item.areaId}>{item.areaName}</Option>
                    ))}
                  </HOCSelect>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="服务类型">
                {getFieldDecorator('contTypes', {
                  rules: [{ required: true, message: '请选择服务类型' }],
                })(
                  <HOCSelect placeholder="请选择服务类型" mode="multiple">
                    {contList.map(item => (
                      <Option key={item.contType}>{item.contName}</Option>
                    ))}
                  </HOCSelect>
                )}
              </Form.Item>
            </Form>
            <div style={{ marginTop: 100, textAlign: 'center' }}>
              <Button onClick={() => router.goBack()} style={{ marginRight: 8 }}>
                返回
              </Button>
              <Button type="primary" onClick={this.onNext}>
                下一步
              </Button>
            </div>
            <Divider dashed style={{ marginTop: 100 }} />
            <p style={{ margin: '0 auto', width: '50%', fontSize: 14 }}>
              说明
              <br />
              不同地区所需的材料不同，所以下载的模版也不相同。部分地区不同合同类型所需材料也不相同，具体来源于入职材料管理。
            </p>
          </StepItem>
          <FileUpload
            title="上传员工信息"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: downTem,
              url: '/esApi/entry/downloadEntryTemplate',
              type: 'POST',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            progressPercent={progressPercent || 0}
            progressTitle="批量办理"
            progressVisible={showProgress}
            isExact={isExactDiv}
          />
          <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
